#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<openssl/rsa.h>
#include<openssl/pem.h>
#include<openssl/err.h>
#define BUFFSIZE 1024

char* encrypt(char *str,char *path_key);//加密
char* decrypt(char *str,char *path_key);//解密
void rsafree(char *p);
#define OPENSSLKEY "test.key"
#define PUBLICKEY "test_pub.key"
/*
int main(void){
    char *source="11111111111111111111111111111111";
    //char *source="i like dancing !";
    char *ptr_en,*ptr_de,*ptmp;
	int i=0;
    printf("source is:%s\n",source);
    ptr_en=encrypt(source,PUBLICKEY);
	ptmp = ptr_en;
    //printf("after encrypt:%s\n\n",ptr_en);
	while(*ptmp != '\0')
		printf("%0x ",0xff&*ptmp++);
    ptr_de=decrypt(ptr_en,OPENSSLKEY);
    printf("\nafter decrypt:%s\n",ptr_de);
    rsafree(ptr_en);
    rsafree(ptr_de);
    return 0;
}
*/
void rsafree(char *p)
{
	if(p)
		free(p);
}
char *encrypt(char *str,char *path_key){
    char *p_en,*ptmp = str;
    RSA *p_rsa;
    FILE *file;
    int flen,rsa_len;
	printf("clear:\n");
	while(*ptmp != '\0')
		printf("%02x ",0xff&*ptmp++);
    if((file=fopen(path_key,"r"))==NULL){
        perror("open key file error");
        return NULL;    
    }   
    if((p_rsa=PEM_read_RSA_PUBKEY(file,NULL,NULL,NULL))==NULL){
    //if((p_rsa=PEM_read_RSAPublicKey(file,NULL,NULL,NULL))==NULL){   换成这句死活通不过，无论是否将公钥分离源文件
        ERR_print_errors_fp(stdout);
        return NULL;
    }   
    flen=strlen(str);
    rsa_len=RSA_size(p_rsa);
	printf("\nenc rsa_len:%d\n",rsa_len);
    p_en=(unsigned char *)malloc(rsa_len+1);
    memset(p_en,0,rsa_len+1);
    if(RSA_public_encrypt(rsa_len,(unsigned char *)str,(unsigned char*)p_en,p_rsa,RSA_NO_PADDING)<0){//RSA_NO_PADDING 
        return NULL;
    }
	ptmp=p_en;
	printf("\ncipher:\n");
	while(*ptmp != '\0')
		printf("%02x ",0xff&*ptmp++);
    RSA_free(p_rsa);
    fclose(file);
    return p_en;
}
char *decrypt(char *str,char *path_key){
    char *p_de,*ptmp=str;
    RSA *p_rsa;
    FILE *file;
    int rsa_len;
	printf("\ncipher:\n");
	while(*ptmp != '\0')
		printf("%02x ",0xff&*ptmp++);
    if((file=fopen(path_key,"r"))==NULL){
        perror("open key file error");
        return NULL;
    }
    if((p_rsa=PEM_read_RSAPrivateKey(file,NULL,NULL,NULL))==NULL){
        ERR_print_errors_fp(stdout);
        return NULL;
    }
    rsa_len=RSA_size(p_rsa);
	printf("\ndec rsa_len:%d\n",rsa_len);
    p_de=(unsigned char *)malloc(rsa_len+1);
    memset(p_de,0,rsa_len+1);
    if(RSA_private_decrypt(rsa_len,(unsigned char *)str,(unsigned char*)p_de,p_rsa,RSA_NO_PADDING)<0){//RSA_PKCS1_PADDING
        return NULL;
    }
	ptmp=p_de;
	printf("\nclear:\n");
	while(*ptmp != '\0')
		printf("%02x ",0xff&*ptmp++);
    RSA_free(p_rsa);
    fclose(file);
    return p_de;
}
